
package com.jf.cloud.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.jf.cloud.api.feign.SearchOrderRefundFeignClient;
import com.jf.cloud.api.multishop.bo.ShopWalletBO;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.feign.ShopWalletFeignClient;
import com.jf.cloud.api.multishop.feign.ShopWalletLogFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.order.constant.BuyerReasonType;
import com.jf.cloud.api.order.dto.FormExcelDTO;
import com.jf.cloud.api.order.vo.*;
import com.jf.cloud.api.user.bo.UserOrderStatisticBO;
import com.jf.cloud.api.user.bo.UserOrderStatisticListBO;
import com.jf.cloud.api.user.dto.MemberReqDTO;
import com.jf.cloud.api.user.vo.UserManagerVO;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.dto.OrderRefundSearchDTO;
import com.jf.cloud.common.order.dto.OrderSearchDTO;
import com.jf.cloud.common.order.vo.EsOrderRefundVO;
import com.jf.cloud.common.order.vo.OrderActivityVO;
import com.jf.cloud.common.order.vo.OrderCountVO;
import com.jf.cloud.common.order.vo.UserOrderStatisticVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.Arith;
import com.jf.cloud.common.util.DateUtils;
import com.jf.cloud.order.manager.MongoOrderManager;
import com.jf.cloud.order.manager.MongoOrderRefundManager;
import com.jf.cloud.order.service.OrderStatisticsService;
import com.jf.cloud.order.vo.OrderOverviewVO;
import com.jf.cloud.order.vo.OrderRefundStatisticsVO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zz
 */
@Service
public class OrderStatisticsServiceImpl implements OrderStatisticsService {

    @Autowired
    private MongoOrderRefundManager mongoOrderRefundManager;

    @Autowired
    private MongoOrderManager mongoOrderManager;

    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ShopWalletLogFeignClient shopWalletLogFeignClient;

    @Autowired
    private SearchOrderRefundFeignClient searchOrderRefundFeignClient;

    public static final Logger log = LoggerFactory.getLogger(OrderStatisticsServiceImpl.class);

    @Override
    public OrderCountVO getOrderCountOfStatusByShopId(Long shopId) {
        OrderCountVO orderCountVO = mongoOrderManager.getOrderCountOfStatusByShopId(shopId);
//        Integer orderRefundCount = mongoOrderRefundManager.getOrderRefundCountOfStatusByShopId(shopId);
        // 暂时改为es进行统计退款数量
        OrderRefundSearchDTO searchDTO = new OrderRefundSearchDTO();
        searchDTO.setShopId(shopId);
        searchDTO.setReturnMoneySts(1);
        searchDTO.setSysType(AuthUserContext.get().getSysType());
        EsPageVO<EsOrderRefundVO> data = searchOrderRefundFeignClient.pageOrderRefund(searchDTO).getData();
        // 获取退款数量
        orderCountVO.setRefund(Integer.parseInt(String.valueOf(data.getTotal())));
        return orderCountVO;
    }

    @Override
    public List<OrderRefundStatisticsVO> listOrderRefundInfoInDateRange(Long shopId, Date endTime, Integer dayCount) {
        Date startTime = this.getStartTime(endTime, dayCount);
        // 根据时间范围查询订单概况与退款数据
        List<OrderRefundStatisticsVO> orderRefundStatisticsVOList = mongoOrderRefundManager.listOrderRefundInfoByShopIdAndDateRange(shopId, startTime, endTime, dayCount);
        List<OrderOverviewVO> orderOverviewVOList = mongoOrderManager.listOrderOverviewInfoByShopIdAndDateRange(shopId, startTime, endTime, dayCount);
        Map<?, OrderRefundStatisticsVO> orderRefundStatisticsMap = orderRefundStatisticsVOList.stream().collect(Collectors.toMap(OrderRefundStatisticsVO::getRefundDateToString, o -> o));
        Map<?, OrderOverviewVO> orderOverviewMap = orderOverviewVOList.stream().collect(Collectors.toMap(OrderOverviewVO::getTimeData, o -> o));
        // 返回结果
        List<OrderRefundStatisticsVO> refundStatisticsVOList = new ArrayList<>();
        // 处理数据
        for (int i = 0; i < dayCount; i++) {
            OrderRefundStatisticsVO resItem = new OrderRefundStatisticsVO();
            // 日期key
            String dateKey = DateUtils.dateToStrYmd(startTime);
            OrderOverviewVO orderOverviewVO = orderOverviewMap.get(dateKey);
            OrderRefundStatisticsVO refundStatisticsVO = orderRefundStatisticsMap.get(dateKey);

            if (Objects.nonNull(orderOverviewVO)) {
                resItem.setTotalOrderCount(orderOverviewVO.getPayOrderCount());
                if (Objects.nonNull(refundStatisticsVO)) {
                    resItem.setRefundRate(this.getRatioRate(refundStatisticsVO.getRefundCount(), orderOverviewVO.getPayOrderCount()));
                    resItem.setPayActualTotal(refundStatisticsVO.getPayActualTotal());
                    resItem.setRefundCount(refundStatisticsVO.getRefundCount());
                } else {
                    resItem.setRefundRate(0.0);
                    resItem.setPayActualTotal(0L);
                    resItem.setRefundCount(0);
                }
            } else {
                resItem.setTotalOrderCount(0);
                if (Objects.nonNull(refundStatisticsVO)) {
                    resItem.setRefundRate(100.00);
                    resItem.setPayActualTotal(refundStatisticsVO.getPayActualTotal());
                    resItem.setRefundCount(refundStatisticsVO.getRefundCount());
                } else {
                    resItem.setRefundRate(0.0);
                    resItem.setPayActualTotal(0L);
                    resItem.setRefundCount(0);
                }
            }
            resItem.setRefundDateToString(dateKey);
            refundStatisticsVOList.add(resItem);
            startTime = getNextTime(startTime);
        }
        return refundStatisticsVOList;
    }

    @Override
    public List<OrderRefundStatisticsVO> listRefundRankingByProd(Long shopId, Date endTime, Integer dayCount) {
        Date startTime = this.getStartTime(endTime, dayCount);
        List<OrderRefundStatisticsVO> orderRefundStatisticsList = mongoOrderRefundManager.listRefundRankingByProd(shopId, startTime, endTime);
        return orderRefundStatisticsList;
    }

    @Override
    public OrderOverviewVO getToDayInfoByHour(Long shopId, Date startTime, Date endTime) {
        OrderOverviewVO orderOverviewVO = this.getOrderStatisticsByShopIdAndDateRange(shopId, startTime, endTime);
        List<Double> actualList = this.getActualByHour(shopId, startTime, endTime);
        orderOverviewVO.setPayActualList(actualList);
        return orderOverviewVO;
    }

    @Override
    public OrderOverviewVO getCurrentMonthByDay(Long shopId, Date startTime, Date endTime) {
        OrderOverviewVO orderOverviewVO = this.getOrderStatisticsByShopIdAndDateRange(shopId, startTime, endTime);
        this.getOrderInfoByDayCount(shopId, endTime, Calendar.getInstance().get(Calendar.DAY_OF_MONTH), orderOverviewVO);
        return orderOverviewVO;
    }

    @Override
    public List<OrderRefundStatisticsVO> listRefundRankingByReason(Long shopId, Date endTime, int dayCount) {
        Date startTime = this.getStartTime(endTime, dayCount);
        List<OrderRefundStatisticsVO> ranking = mongoOrderRefundManager.listRefundRankingByReason(shopId, startTime, endTime);
        Integer totalRefundCount = 0;
        for (OrderRefundStatisticsVO orderRefundStatisticsVO : ranking) {
            totalRefundCount += orderRefundStatisticsVO.getRefundCount();
        }
        for (OrderRefundStatisticsVO orderRefundStatisticsVO : ranking) {
            try {
                BuyerReasonType reasonType = BuyerReasonType.instance(Integer.valueOf(orderRefundStatisticsVO.getBuyerReason()));
                if (Objects.nonNull(reasonType)) {
                    orderRefundStatisticsVO.setBuyerReason(reasonType.getCn());
                }
            } catch (NumberFormatException numberFormatException) {
                log.error(numberFormatException.getMessage(), numberFormatException);
            }
            orderRefundStatisticsVO.setRefundRate(Arith.div(Arith.mul(orderRefundStatisticsVO.getRefundCount() , 100), totalRefundCount, 2));
        }
        return ranking;
    }

    @Override
    public OrderOverviewVO getDetailInfoByHour(Long shopId) {
        Date now = new Date();
        // 获取今天的订单概况
        OrderOverviewVO toDayInfoByHour = this.getOrderStatisticsByShopIdAndDateRange(shopId, DateUtil.beginOfDay(now), DateUtil.endOfDay(now));
        // 获取昨天的订单概况
        OrderOverviewVO yesToDayInfoByHour = this.getOrderStatisticsByShopIdAndDateRange(shopId, DateUtil.beginOfDay(DateUtils.getBeforeDay(now, -1)), DateUtil.endOfDay(DateUtils.getBeforeDay(now, -1)));
        // 获取今天的支付金额列表
        List<Double> toDayActualList = this.getActualByHour(shopId, DateUtil.beginOfDay(DateUtil.date()), DateUtil.endOfDay(DateUtil.date()));
        // 获取昨天的支付金额列表
        List<Double> yesToDayActualList = this.getActualByHour(shopId, DateUtil.beginOfDay(DateUtils.getBeforeDay(now, -1)), DateUtil.endOfDay(DateUtils.getBeforeDay(now, -1)));
        // 获取今天的收款码金额
//        ShopWalletBO shopWalletBO=shopWalletLogFeignClient.getQrCodeStatisticsByShopIdAndDateRange( DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).getData();
//        toDayInfoByHour.setQrCodePayActual(shopWalletBO.getTotalSettledAmount());
        toDayInfoByHour.setPayActualList(toDayActualList);
        toDayInfoByHour.setYesterdayPayActualList(yesToDayActualList);
        // 计算今天与昨天数值变化的比率
        toDayInfoByHour.setYesterdayPayUserRate(this.getChangeRate(toDayInfoByHour.getPayUserCount(), yesToDayInfoByHour.getPayUserCount()));
        toDayInfoByHour.setYesterdayPayOrderRate(this.getChangeRate(toDayInfoByHour.getPayOrderCount(), yesToDayInfoByHour.getPayOrderCount()));
        toDayInfoByHour.setYesterdayRefundRate(this.getChangeRate(toDayInfoByHour.getRefund(), yesToDayInfoByHour.getRefund()));
        toDayInfoByHour.setYesterdayOnePriceRate(this.getChangeRate(toDayInfoByHour.getOnePrice(), yesToDayInfoByHour.getOnePrice()));
        toDayInfoByHour.setYesterdayPayActualRate(this.getChangeRate(toDayInfoByHour.getPayActual(), yesToDayInfoByHour.getPayActual()));
        return toDayInfoByHour;
    }

    @Override
    public List<OrderOverviewVO> listSpuRankingByOrderCount(Long shopId, Date endTime, int dayCount, int limit) {
        Date startTime = this.getStartTime(endTime, dayCount);
        List<OrderOverviewVO> orderOverviews = mongoOrderManager.listSpuRankingByOrderCount(shopId, startTime, endTime, limit);
        return orderOverviews;
    }

    @Override
    public List<OrderOverviewVO> listShopRankingByPayActual(Date endTime, int dayCount, int limit) {
        Date startTime = this.getStartTime(endTime, dayCount);
        List<OrderOverviewVO> orderOverviewVOList = mongoOrderManager.listShopRankingByPayActual(startTime, endTime, limit);
        if (CollUtil.isEmpty(orderOverviewVOList)) {
            // 数据为空，直接返回
            log.info("listShopRankingByPayActual 数据为空，直接返回");
            return orderOverviewVOList;
        }
        List<Long> shopIds = orderOverviewVOList.stream().map(OrderOverviewVO::getShopId).collect(Collectors.toList());
        ServerResponseEntity<List<ShopDetailVO>> listServerResponseEntity = shopDetailFeignClient.listByShopIds(shopIds);
        if (listServerResponseEntity.isFail()) {
            throw new LuckException(listServerResponseEntity.getMsg());
        }
        if (CollUtil.isEmpty(listServerResponseEntity.getData())) {
            return new ArrayList<>();
        }
        // 赋值店铺名称
        Map<Long, ShopDetailVO> shopDetailMap = listServerResponseEntity.getData().stream().collect(Collectors.toMap(ShopDetailVO::getShopId, p -> p));
        Iterator<OrderOverviewVO> iterator = orderOverviewVOList.iterator();
        while (iterator.hasNext()) {
            OrderOverviewVO orderOverviewVO = iterator.next();
            if (Objects.isNull(shopDetailMap.get(orderOverviewVO.getShopId()))) {
                iterator.remove();
                continue;
            }
            orderOverviewVO.setShopName(shopDetailMap.get(orderOverviewVO.getShopId()).getShopName());
        }
        return orderOverviewVOList;
    }

    @Override
    public List<OrderRefundStatisticsVO> listShopRankingByRefundCount(Date endTime, Integer dayCount, Integer limit) {
        Date startTime = this.getStartTime(endTime, dayCount);
        List<OrderRefundStatisticsVO> orderRefundStatisticsVOList = mongoOrderRefundManager.listShopRankingByRefundCount(startTime, endTime, limit);
        if (CollUtil.isEmpty(orderRefundStatisticsVOList)) {
            // 数据为空，直接返回
            log.info("listShopRankingByRefundCount 数据为空，直接返回");
            return orderRefundStatisticsVOList;
        }
        List<Long> shopIds = orderRefundStatisticsVOList.stream().map(OrderRefundStatisticsVO::getShopId).collect(Collectors.toList());
        ServerResponseEntity<List<ShopDetailVO>> listServerResponseEntity = shopDetailFeignClient.listByShopIds(shopIds);
        if (listServerResponseEntity.isFail()) {
            throw new LuckException(listServerResponseEntity.getMsg());
        }
        if (CollUtil.isEmpty(listServerResponseEntity.getData())) {
            log.info("listShopRankingByRefundCount 店铺数据为空，直接返回");
            return new ArrayList<>(0);
        }
        // 赋值店铺名称
        Map<Long, ShopDetailVO> shopDetailMap = listServerResponseEntity.getData().stream().collect(Collectors.toMap(ShopDetailVO::getShopId, p -> p));
        Iterator<OrderRefundStatisticsVO> iterator = orderRefundStatisticsVOList.iterator();
        while (iterator.hasNext()) {
            OrderRefundStatisticsVO orderRefundStatisticsVO = iterator.next();
            if (Objects.isNull(shopDetailMap.get(orderRefundStatisticsVO.getShopId()))) {
                iterator.remove();
                continue;
            }
            orderRefundStatisticsVO.setShopName(shopDetailMap.get(orderRefundStatisticsVO.getShopId()).getShopName());
        }
        return orderRefundStatisticsVOList;
    }

    @Override
    public OrderOverviewVO getOrderInfoByDayCountAndShopId(Long shopId, Integer dayCount) {
        Date endTime = DateUtil.endOfDay(DateUtil.date());
        Date startTime = this.getStartTime(endTime, dayCount);
        OrderOverviewVO orderOverviewVO = this.getOrderStatisticsByShopIdAndDateRange(shopId, startTime, endTime);
        this.getOrderInfoByDayCount(shopId, endTime, dayCount, orderOverviewVO);
        return orderOverviewVO;
    }

    @Override
    public List<UserOrderStatisticVO> countOrderByUserIds(List<Long> userIds, Long shopId) {
        // 统计用户的订单相关信息
        // es一个月内的，直接查数据库(一个月后的数据进行冷备)，一个月之前的数据查es
        // 所以需要将数据库中的订单信息和es中的订单加起来才行完整的订单信息

        // 查询数据库中订单信息
        List<UserOrderStatisticVO> orderStatisticList = mongoOrderManager.statisticalUserOrderData(userIds, shopId);
        List<UserOrderStatisticVO> orderRefundStatisticList = mongoOrderRefundManager.statisticalUserOrderData(userIds, shopId);
        List<UserOrderStatisticVO> totalOrderTimesList = mongoOrderManager.getShopOrderCountByUserIdAndShopId(userIds, shopId);

        if (CollUtil.isEmpty(orderStatisticList)) {
            return orderStatisticList;
        }

        Map<Long, UserOrderStatisticVO> map = orderRefundStatisticList.stream().collect(Collectors.toMap(UserOrderStatisticVO::getUserId, u -> u));
        Map<Long, UserOrderStatisticVO> totalOrderTimesMap = totalOrderTimesList.stream().collect(Collectors.toMap(UserOrderStatisticVO::getUserId, u -> u));
        for (UserOrderStatisticVO userOrderStatisticVO : orderStatisticList) {
            if(!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)){
                userOrderStatisticVO.setAllCount(totalOrderTimesMap.get(userOrderStatisticVO.getUserId()).getAllCount());
            }
            if (!map.containsKey(userOrderStatisticVO.getUserId())) {
                userOrderStatisticVO.setAfterSaleAmount(new BigDecimal(0));
                userOrderStatisticVO.setAfterSaleTimes(0);
                continue;
            }
            UserOrderStatisticVO userOrderRefund = map.get(userOrderStatisticVO.getUserId());
            userOrderStatisticVO.setAfterSaleAmount(userOrderRefund.getAfterSaleAmount());
            userOrderStatisticVO.setAfterSaleTimes(userOrderRefund.getAfterSaleTimes());
        }


        // 暂时无冷备策略，下面的代码不执行，等有了冷备策略后再执行

        // 从es中聚合多个用户的订单信息
//        ServerResponseEntity<List<UserOrderStatisticVO>> orderStatisticResponse = searchOrderFeignClient.countOrderByUserIds(userIds);
//        if (orderStatisticResponse.isSuccess()) {
//            // 将订单数据整合到一起
//            List<UserOrderStatisticVO> data = orderStatisticResponse.getData();
//            if (CollUtil.isEmpty(data)) {
//                return orderStatisticList;
//            }
//            Map<Long, UserOrderStatisticVO> orderStatisticMap = data.stream().collect(Collectors.toMap(UserOrderStatisticVO::getUserId, (k) -> k));
//            for (UserOrderStatisticVO orderStatisticVO : orderStatisticList) {
//                Long userId = orderStatisticVO.getUserId();
//                UserOrderStatisticVO statisticVO = orderStatisticMap.get(userId);
//                if (Objects.isNull(statisticVO)) {
//                    continue;
//                }
//                // 消费金额
//                BigDecimal consAmountEs = statisticVO.getConsAmount();
//                if (Objects.nonNull(consAmountEs)) {
//                    BigDecimal consAmount = orderStatisticVO.getConsAmount();
//                    orderStatisticVO.setActualAmount(consAmount.add(consAmountEs));
//                }
//                // 平均折扣 ，reduceAmount/consTimes
//                BigDecimal reduceAmountEs = statisticVO.getReduceAmount();
//                int consTimes = statisticVO.getConsTimes();
//                if (Objects.nonNull(reduceAmountEs)) {
//                    BigDecimal reduceAmount = orderStatisticVO.getReduceAmount();
//                    consTimes = consTimes + orderStatisticVO.getConsTimes();
//                    if (consTimes > 0) {
//                        BigDecimal averDiscount = reduceAmount.add(reduceAmountEs).divide(new BigDecimal(Integer.toString(consTimes)), 0, BigDecimal.ROUND_HALF_UP);
//                        orderStatisticVO.setAverDiscount(averDiscount);
//                    }
//                    orderStatisticVO.setConsTimes(consTimes);
//                }
//                // 实付金额
//                BigDecimal actualAmountEs = statisticVO.getActualAmount();
//                if (Objects.nonNull(actualAmountEs)) {
//                    orderStatisticVO.setActualAmount(orderStatisticVO.getActualAmount().add(actualAmountEs));
//                }
//                // 最新消费时间, 根据es中order的冷备逻辑，es中存储的是之前的数据
//                // 从数据库中统计的消费时间必定是最新的消费时间
//                // 所以只需要判断，如果数据库中没有最新消费时间，而es中有最新消费时间，就用es中的就好了
//                if (Objects.isNull(orderStatisticVO.getReConsTime()) && Objects.nonNull(statisticVO.getReConsTime())) {
//                    orderStatisticVO.setReConsTime(statisticVO.getReConsTime());
//                }
//            }
//        }

        return orderStatisticList;
    }

    @Override
    public UserOrderStatisticBO getPaidMemberByParam(MemberReqDTO param) {
        UserOrderStatisticBO userOrderStatistic = mongoOrderManager.getPaidMemberByParam(param);
        return userOrderStatistic;
    }

    @Override
    public UserOrderStatisticListBO getMemberPayData(MemberReqDTO param) {
        UserOrderStatisticListBO userOrderStatisticListBO = mongoOrderManager.getMemberPayData(param);
        return userOrderStatisticListBO;
    }

    @Override
    public List<Long> getOrderUserIdsBySearchDTO(OrderSearchDTO orderSearchDTO) {
        return mongoOrderManager.getOrderUserIdsBySearchDTO(orderSearchDTO);
    }

    @Override
    public List<Long> listUserIdByPurchaseNum(Integer isPayed, Integer deleteStatus, Date startDate, Date endDate, Integer status, Long minNum, Long maxNum) {
        return mongoOrderManager.listUserIdByPurchaseNum(isPayed, deleteStatus, startDate, endDate, status, minNum, maxNum);
    }

    @Override
    public List<Long> listUserIdByAverageActualTotal(Integer isPayed, Integer deleteStatus, Date startDate, Date endDate, Integer status, Long minAmount, Long maxAmount) {
        return mongoOrderManager.listUserIdByAverageActualTotal(isPayed, deleteStatus, startDate, endDate, status, minAmount, maxAmount);
    }

    @Override
    public List<OrderProdEffectRespVO> getProdEffectByDateAndProdIds(List<Long> spuIds, Date startTime, Date endTime) {
        return mongoOrderManager.getProdEffectByDateAndProdIds(spuIds, startTime, endTime);
    }

    @Override
    public List<FlowOrderVO> listFlowOrderByOrderIds(Collection<Long> orderIds) {
        return mongoOrderManager.listFlowOrderByOrderIds(orderIds);
    }

    @Override
    public List<Long> getInsightSpuIdsByDate(Integer begin, Integer size, Long shopId, Date startTime, Date endTime) {
        return mongoOrderManager.getInsightSpuIdsByDate(begin, size, shopId, startTime, endTime);
    }

    @Override
    public List<SumAmountVO> listSumDataByUserIds(List<Long> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        return mongoOrderManager.listSumDataByUserIds(userIds);
    }

    @Override
    public Long hasBuySuccessProd(Long spuId, Long userId) {
        return mongoOrderManager.hasBuySuccessProd(spuId, userId);
    }

    @Override
    public UserShoppingDataVO calculateUserInShopData(Long userId) {
        return mongoOrderManager.calculateUserInShopData(userId);
    }

    @Override
    public List<OrderActivityVO> getActivitySalesQuantity(List<Long> activityIds, Integer activityType) {
        return mongoOrderManager.getActivitySalesQuantity(activityIds, activityType);
    }

    @Override
    public Long countActivityOrderSale(Long skuId, Long activityId, Integer activityType) {
        // 查询sku销量不需要缓存
        if (Objects.nonNull(skuId)) {
            return mongoOrderManager.countActivityOrderSale(skuId, activityId, activityType);
        }
        // 查询活动的销量，实时性要求不高，可以通过缓存获取
        String key = "ACTIVETY_ORDER_SALE" + CacheNames.UNION_KEY + activityId + CacheNames.UNION_KEY + activityType;
        return getActivityOrderSaleCache(key, skuId, activityId, activityType);
    }

    @Override
    public AccountOrderDetailVO getAccountOrderDetail(Date startTime, Date endTime, String shopName, Long shopId) {
        return mongoOrderManager.getAccountOrderDetail(startTime, endTime, shopName, shopId);
    }

    @Override
    public PageShopAccountOrderVO listShopAccountDetail(Date startTime, Date endTime, String shopName, Integer pageSize, Integer pageNum) {
        return mongoOrderManager.listShopAccountDetail(startTime, endTime, shopName, pageSize, pageNum);
    }

    @Override
    public PageShopAccountOrderVO listOrderPayInfo(Date startTime, Date endTime, Long shopId, String shopName, Integer pageSize, Integer pageNum) {
        if (Objects.isNull(pageNum) && Objects.isNull(pageSize)) {
           return mongoOrderManager.listOrderPayInfo(startTime, endTime, shopName);
        }
        return mongoOrderManager.pageOrderPayInfo(startTime, endTime, shopId, pageSize, pageNum);
    }

    @Override
    public List<Long> addSoldNumRankCacheByShopIdAndTime(String key, Long shopId, Integer time, Integer expireTime, Integer esRenovationSpuSort, Long primaryCategoryId) {
        List<Long> spuIds = RedisUtil.getListRange(key,0L,10L);

        if (CollectionUtil.isNotEmpty(spuIds)) {
            return spuIds;
        }

        // 加锁，防止缓存击穿
        RLock rLock = redissonClient.getLock("redisson_lock:sold_num_rank:" + key);
        try {
            int lockWait = 30;
            if (rLock.tryLock(lockWait, lockWait, TimeUnit.SECONDS)) {
                spuIds = RedisUtil.getListRange(key,0L,10L);
                if (CollectionUtil.isEmpty(spuIds)) {
                    spuIds = mongoOrderManager.getSoldNumRankCacheByShopIdAndTime(shopId, time,esRenovationSpuSort, primaryCategoryId);
                    return spuIds;
//                    RedisUtil.leftPushAll(key, spuIds, expireTime);
                }
            } else {
                throw new LuckException("网络繁忙，请稍后再试");
            }
        } catch (InterruptedException e) {
            log.error("InterruptedException:", e);
        } finally {
            try {
                if (rLock.isLocked()) {
                    rLock.unlock();
                }
            } catch (Exception e) {
                log.error("Exception:", e);
            }
        }
        return spuIds;
    }

    @Override
    public GroupInfoVO getGroupInfo(Long groupActivityId) {
        return mongoOrderManager.getGroupInfo(groupActivityId);
    }

    @Override
    public List<FormExcelDTO> listFormExcel(FormExcelParamVO formExcelParamVO) {
        return mongoOrderManager.listFormExcel(formExcelParamVO);
    }

    @Override
    public List<UserManagerVO> listOrderByUserIdsAndShopId(PageDTO pageDTO, List<Long> userIds, Long shopId, Integer sort) {
        List<UserManagerVO> orderStatisticList = mongoOrderManager.listStatisticalUserOrderData(userIds, shopId, sort);
        List<Long> ids = orderStatisticList.stream().map(UserManagerVO::getUserId).collect(Collectors.toList());
        List<UserOrderStatisticVO> orderRefundStatisticList = mongoOrderRefundManager.statisticalUserOrderData(ids,shopId);
        List<UserOrderStatisticVO> totalOrderTimesList = mongoOrderManager.getShopOrderCountByUserIdAndShopId(ids, shopId);

        if (CollUtil.isEmpty(orderStatisticList)) {
            return new ArrayList<>();
        }

        Map<Long, UserOrderStatisticVO> map = orderRefundStatisticList.stream().collect(Collectors.toMap(UserOrderStatisticVO::getUserId, u -> u));
        Map<Long, UserOrderStatisticVO> totalOrderTimesMap = totalOrderTimesList.stream().collect(Collectors.toMap(UserOrderStatisticVO::getUserId, u -> u));
        for (UserManagerVO userOrderStatisticVO : orderStatisticList) {
            if(!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)){
                userOrderStatisticVO.setAllCount(totalOrderTimesMap.get(userOrderStatisticVO.getUserId()).getAllCount());
            }
            if (!map.containsKey(userOrderStatisticVO.getUserId())) {
                userOrderStatisticVO.setAfterSaleAmount(new BigDecimal(0));
                userOrderStatisticVO.setAfterSaleTimes(0);
                continue;
            }
            UserOrderStatisticVO userOrderRefund = map.get(userOrderStatisticVO.getUserId());
            userOrderStatisticVO.setAfterSaleAmount(userOrderRefund.getAfterSaleAmount());
            userOrderStatisticVO.setAfterSaleTimes(userOrderRefund.getAfterSaleTimes());
        }


        return orderStatisticList;

    }

    private Long getActivityOrderSaleCache(String key, Long skuId, Long activityId, Integer activityType) {
        Long activityOrderSale = RedisUtil.getLongValue(key);

        if (Objects.nonNull(activityOrderSale)) {
            return activityOrderSale;
        }

        // 加锁，防止缓存击穿
        RLock rLock = redissonClient.getLock("redisson_lock:order_sale:" + activityType + CacheNames.UNION_KEY + activityId);
        try {
            int lockWait = 1;
            if (rLock.tryLock(lockWait, lockWait, TimeUnit.SECONDS)) {
                activityOrderSale = RedisUtil.getLongValue(key);
                if (activityOrderSale == null) {
                    activityOrderSale = mongoOrderManager.countActivityOrderSale(skuId, activityId, activityType);
                    RedisUtil.setLongValue(key, activityOrderSale, 1);
                }
            } else {
                throw new LuckException("网络繁忙，请稍后再试");
            }
        } catch (InterruptedException e) {
            log.error("InterruptedException:", e);
        } finally {
            try {
                if (rLock.isLocked()) {
                    rLock.unlock();
                }
            } catch (Exception e) {
                log.error("Exception:", e);
            }
        }
        return activityOrderSale;
    }


    /**
     * 根据店铺Id与时间范围获取订单概况信息
     *
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    private OrderOverviewVO getOrderStatisticsByShopIdAndDateRange(Long shopId, Date startTime, Date endTime) {
        OrderOverviewVO orderOverviewVO = mongoOrderManager.getOrderOverviewInfoByShopId(shopId, startTime, endTime);
        OrderRefundStatisticsVO orderRefundStatisticsVO = mongoOrderRefundManager.getOrderRefundInfoByShopId(shopId, startTime, endTime);
        double onePrice = (orderOverviewVO.getPayUserCount() == 0) ?
                0 : (Arith.div(orderOverviewVO.getPayActual(), orderOverviewVO.getPayUserCount(), 2));
        orderOverviewVO.setOnePrice(onePrice);
        orderOverviewVO.setRefund(orderRefundStatisticsVO.getPayActualTotal());
        orderOverviewVO.setChargebackCount(orderRefundStatisticsVO.getRefundCount());
        return orderOverviewVO;
    }

    /**
     * 根据店铺Id与时间范围按小时分段获取数据支付金额列表
     *
     * @param shopId
     * @param startTime
     * @param endTime
     */
    private List<Double> getActualByHour(Long shopId, Date startTime, Date endTime) {
        List<OrderOverviewVO> orderOverviewVOList = mongoOrderManager.listActualByHour(shopId, startTime, endTime);
        Map<Integer, Double> payMap = new HashMap<>(30);
        for (OrderOverviewVO temp : orderOverviewVOList) {
            payMap.put(Integer.parseInt(temp.getTimeData()), temp.getPayActual());
        }
        List<Double> nowActual = new ArrayList<>();
        double sum = 0.00;
        for (int i = 0; i < Constant.MAX_HOUR_NUM_BY_DAY; i++) {
            if (payMap.get(i) != null) {
                sum = Arith.add(sum, Arith.div(payMap.get(i), 100, 2));
            }
            nowActual.add(Arith.round(sum, 2));
        }
        return nowActual;
    }

    /**
     * 根据店铺Id与时间范围按天分段获取支付金额列表
     *
     * @param shopId
     * @param dayCount
     * @param endTime
     * @param orderOverviewVO
     */
    private void getOrderInfoByDayCount(Long shopId, Date endTime, Integer dayCount, OrderOverviewVO orderOverviewVO) {
        Date startTime = this.getStartTime(endTime, dayCount);
        // 获取支付金额列表
        List<OrderOverviewVO> orderOverviewVOList = mongoOrderManager.listOrderOverviewInfoByShopIdAndDateRange(shopId, startTime, endTime, dayCount);
        Map<?, OrderOverviewVO> orderOverviewMap = orderOverviewVOList.stream().collect(Collectors.toMap(OrderOverviewVO::getTimeData, o -> o));

        List<Double> actualList = new ArrayList<>();
        List<String> dateToStringList = new ArrayList<>();

        for (int i = 0; i < dayCount; i++) {
            if (orderOverviewMap.containsKey(DateUtils.dateToStrYmd(startTime))) {
                OrderOverviewVO overviewVO = orderOverviewMap.get(DateUtils.dateToStrYmd(startTime));
                actualList.add(Arith.div(overviewVO.getPayActual(), 100, 2));
            } else {
                actualList.add(0.0);
            }
            dateToStringList.add(DateUtils.dateToStrYmd(startTime));
            startTime = getNextTime(startTime);
        }

        orderOverviewVO.setDateToStringList(dateToStringList);
        orderOverviewVO.setPayActualList(actualList);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        // 获取本月的第几天
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);

        if (dayCount <= monthDay) {
            orderOverviewVO.setCurrentMonthPayActual(orderOverviewVO.getPayActual());
        } else {
            double currentMonthPayActual = 0L;
            // 累加本月支付金额
            for (int i = actualList.size() - 1, j = 0; j < monthDay && i >= 0; j++, i--) {
                currentMonthPayActual = Arith.add(currentMonthPayActual, actualList.get(i));
            }
            orderOverviewVO.setCurrentMonthPayActual(currentMonthPayActual);
        }
    }

    /**
     * 根据结束时间与天数获取起始时间
     *
     * @param endTime
     * @param dayCount
     * @return
     */
    private Date getStartTime(Date endTime, Integer dayCount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        calendar.add(Calendar.DATE, -dayCount + 1);
        return DateUtil.beginOfDay(calendar.getTime());
    }

    private Double getChangeRate(double nowValue, double oldValue) {
        if (Objects.equals(oldValue, 0.0)) {
            return Objects.equals(nowValue, 0.0) ? 0.0 : 1.0;
        }
        double minus = Arith.sub(nowValue, oldValue);
        return Arith.div(minus, oldValue, 4);
    }

    /**
     * 获取下一次循环的开始时间，以及设置后台显示的时间字符串
     *
     * @param startTime 开始时间
     * @return
     */
    private Date getNextTime(Date startTime) {
        startTime = DateUtil.offsetDay(startTime, 1);
        return startTime;
    }

    /**
     * 计算两个数的百分比
     *
     * @param dividend 被除数
     * @param divisor  除数
     * @return
     */
    private Double getRatioRate(Integer dividend, Integer divisor) {
        if (Objects.isNull(dividend) || dividend == 0.0) {
            return 0.0;
        }
        if (Objects.isNull(divisor) || divisor == 0.0) {
            return 100.0;
        }
        return Arith.mul(Arith.div(dividend, divisor, 4), 100.00);
    }
}
